package com.example.tfliteonwatch;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import org.tensorflow.lite.nnapi.NnApiDelegate;
import org.tensorflow.lite.Interpreter;
import org.tensorflow.lite.DataType;
import org.tensorflow.lite.support.common.ops.NormalizeOp;
import org.tensorflow.lite.support.image.ImageProcessor;
import org.tensorflow.lite.support.image.TensorImage;
import org.tensorflow.lite.support.image.ops.ResizeOp;
import org.tensorflow.lite.support.tensorbuffer.TensorBuffer;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;



public class TFLiteLoader {
    private static Context mContext;
    Interpreter mInterpreter;

    private static  TFLiteLoader instance;
    public static TFLiteLoader newInstance (Context context){
        mContext = context;
        if (instance == null){
            instance = new TFLiteLoader();
        }
        return  instance;
    }
    Interpreter get(String modelpath){
//        Interpreter.Options options = new Interpreter.Options();
//        options.setNumThreads(2);  //使用双线程

        try{
//            if(Objects.isNull(mInterpreter))
                mInterpreter = new Interpreter(loadModelFile(mContext,modelpath));

        }catch (IOException e){
            e.printStackTrace();
        }
        return mInterpreter;
    }
    private MappedByteBuffer loadModelFile( Context context ,String modelpath) throws  IOException{
        AssetFileDescriptor fileDescriptor = context.getAssets().openFd(modelpath);
        FileInputStream inputStream = new FileInputStream(fileDescriptor.getFileDescriptor());
        FileChannel fileChannel = inputStream.getChannel();
        long startoffset = fileDescriptor.getStartOffset();
        long declaredLength = fileDescriptor.getDeclaredLength();
        return fileChannel.map(FileChannel.MapMode.READ_ONLY,startoffset,declaredLength);
    }
}
